import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoClient {
    // 声明一个DatagramSocket对象
   DatagramSocket socket;
    //定义端IP
    String serverIp;
    //定义客户端
    int serverport;
    //通过构造方法指定的服务器IP和端口号
    public UDPEchoClient(String serverIp,int serverport) throws SocketException {
        //初始化DatagramSocket
      this.socket=new DatagramSocket();
      this.serverIp=serverIp;
      this.serverport=serverport;
    }

    public void start() throws IOException {
        System.out.println("客户端已启动");
        //循环客户端的输入
        while (true) {
            //获取用户输入
            System.out.println("->");
            Scanner scanner=new Scanner(System.in);
            String request=scanner.nextLine();
            if(request==null||request.isEmpty()){
                System.out.println("输入信息不能为空");
                continue;
            }
            //创建目标的Socketaddress对象
            SocketAddress address=new InetSocketAddress(serverIp,serverport);
            //定义一个包装用户请求数据的DatagramPacket
            DatagramPacket requsetPacket=new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    0,request.length(),address);
            //发送到真实数据到服务器
            socket.send(requsetPacket);
            //用DatagramPacket接收服务器的响应数据
            DatagramPacket resposePacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(resposePacket);
            //解析数据得到响应
            String response=new String(resposePacket.getData(),0,resposePacket.getLength(),"UTF-8");
            System.out.printf("request =%s,respose =%s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient udpEchoClient=new UDPEchoClient("127.0.0.1",8888);
        udpEchoClient.start();
    }

}
